import { ChatMessage } from '@/store/chatStore'
import { FC, useEffect, useState } from 'react'
import { useColorVar, useStyles } from '@/hooks/styles'
import styles from './ChatMessageItem.module.scss'
import { useChatStore, useUserStore } from '@/hooks'
import { getCurrentHourAndMinute } from '@/utils/basic'
import { SvgIcon } from '@/components/icons'
import { LeftBubbleReverseFillet } from '@/components/icons/LeftBubbleReverseFillet'
import { Markdown } from '@/components/Planner/Markdown/Markdown'
import { RightBubbleReverseFillet } from '@/components/icons/RightBubbleReverseFillet'
import { AnimatePresence, motion } from 'framer-motion'
import { motionEasing } from '@/config'
import { Loader } from '@/components/universal/Loader/Loader'
import { Done_16x16 } from '@/components/icons/Done_16x16'
import { Avatar } from '@/components/universal/Avatar/Avatar'
import { observer } from 'mobx-react'

interface IChatMessageItem {
  message: { type: 'human' | 'ai'; content: string }
  ifLast: boolean
}

export const ChatMessageItem: FC<IChatMessageItem> = observer(
  ({ message, ifLast }) => {
    const c = useColorVar()
    const styleClass = useStyles(styles)
    const userStore = useUserStore()
    const chatStore = useChatStore()

    // 消息气泡布局位置（用户气泡靠右）
    const layoutDirection = message['type'] === 'human' ? 'right' : 'left'

    const [showDone, setShowDone] = useState<boolean>(false)

    const [content, setContent] = useState<string>(
      ifLast ? '' : message.content
    )

    useEffect(() => {
      if (message.type === 'ai') {
        if (ifLast) {
          let output = ''
          let index = 0
          let timer = null
          function typeWriter() {
            // 检查索引是否超出文本长度
            if (index < message.content.length) {
              // 逐字截取文本并显示
              const char = message.content.charAt(index)
              output += char
              setContent(output)
              index++

              // 通过递归调用自身设置下一个字符的输出延迟时间
              timer = setTimeout(typeWriter, 45) // 修改这个值可以控制打字速度
            }
          }
          typeWriter()
        }
      }
    }, [chatStore.history])

    return (
      <>
        {layoutDirection === 'left' ? (
          <div {...styleClass(['list-container'], { flexDirection: 'row' })}>
            <motion.div
              {...styleClass(['layout'], { flexDirection: 'row' })}
              initial={{ y: 6, x: -10, opacity: '0%' }}
              animate={{ y: 0, x: 0, opacity: '100%' }}
              transition={{ ...motionEasing, duration: 0.3, delay: 0.1 }}
            >
              <div {...styleClass(['avatar-wrapper'])}>
                <Avatar imgUrl={chatStore.assistantAvatar} />
              </div>
              <div {...styleClass(['bubble-layout'])}>
                <div
                  {...styleClass(['bubble-header-wrapper'], { marginLeft: 16 })}
                >
                  <span {...styleClass(['bubble-header-nickname'])}>
                    {'GPT'}
                  </span>
                  <span {...styleClass(['bubble-header-time'])}>
                    {getCurrentHourAndMinute(Math.floor(Date.now() / 1000))}
                  </span>
                </div>
                <div
                  {...styleClass(['bubble-content-wrapper'], {
                    flexDirection: 'row',
                  })}
                >
                  <SvgIcon icon={LeftBubbleReverseFillet} />
                  <div
                    {...styleClass(['bubble-content-bubble'], {
                      borderRadius: '16px 16px 16px 0',
                      background: c('chatBubble-bg-left'),
                    })}
                  >
                    <Markdown content={content} theme={'light'} />
                  </div>
                </div>
                <div
                  {...styleClass(['bubble-footer-wrapper'], {
                    marginLeft: -6,
                    justifyContent: 'flex-end',
                  })}
                >
                  {(!ifLast || !chatStore.typing) && (
                    <motion.div
                      {...styleClass(['bubble-footer-status'])}
                      initial={{ x: -15, opacity: '0%' }}
                      animate={{ x: 0, opacity: '100%' }}
                      transition={{
                        ...motionEasing,
                        duration: 0.3,
                        delay: 0.75,
                      }}
                    >
                      Delivered
                    </motion.div>
                  )}
                  <AnimatePresence>
                    {showDone && ifLast && (
                      <motion.div
                        {...styleClass(['bubble-footer-loader-wrapper'], {
                          marginLeft: 8,
                        })}
                        initial={{ opacity: '0%', x: -5 }}
                        animate={{ opacity: '100%', x: 0 }}
                        exit={{ opacity: '0%', x: 20, width: 0, marginLeft: 0 }}
                        transition={{
                          ...motionEasing,
                          duration: 0.3,
                          delay: 0.5,
                        }}
                      >
                        <SvgIcon icon={Done_16x16} />
                      </motion.div>
                    )}
                  </AnimatePresence>
                  <AnimatePresence>
                    {chatStore.typing && ifLast && (
                      <motion.div
                        {...styleClass(['bubble-footer-status'])}
                        initial={{ opacity: '100%' }}
                        exit={{ opacity: '0%', x: 15 }}
                        transition={{
                          ...motionEasing,
                          duration: 0.25,
                        }}
                      >
                        Typing...
                      </motion.div>
                    )}
                  </AnimatePresence>
                  <AnimatePresence>
                    {chatStore.typing && ifLast && (
                      <motion.div
                        {...styleClass(['bubble-footer-loader-wrapper'], {
                          marginLeft: 8,
                        })}
                        initial={{ opacity: '100%' }}
                        exit={{ opacity: '0%', x: 15 }}
                        transition={{
                          ...motionEasing,
                          duration: 0.25,
                        }}
                      >
                        <Loader type={'threeBody'} />
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              </div>
            </motion.div>
          </div>
        ) : (
          <div
            {...styleClass(['list-container'], {
              flexDirection: 'row-reverse',
            })}
          >
            <motion.div
              {...styleClass(['layout'], { flexDirection: 'row-reverse' })}
              initial={{ y: 6, x: 10, opacity: '0%' }}
              animate={{ y: 0, x: 0, opacity: '100%' }}
              transition={{ ...motionEasing, duration: 0.3, delay: 0.1 }}
            >
              <div {...styleClass(['avatar-wrapper'])}>
                <Avatar imgUrl={userStore.userInfo.avatar} />
              </div>
              <div {...styleClass(['bubble-layout'])}>
                <div
                  {...styleClass(['bubble-header-wrapper'], {
                    marginLeft: -16,
                    justifyContent: 'flex-end',
                  })}
                >
                  <span {...styleClass(['bubble-header-nickname'])}>
                    {'me'}
                  </span>
                  <span {...styleClass(['bubble-header-time'])}>
                    {getCurrentHourAndMinute(Math.floor(Date.now() / 1000))}
                  </span>
                </div>
                <div
                  {...styleClass(['bubble-content-wrapper'], {
                    flexDirection: 'row-reverse',
                  })}
                >
                  <SvgIcon icon={RightBubbleReverseFillet} />
                  <div
                    {...styleClass(['bubble-content-bubble'], {
                      borderRadius: '16px 16px 0 16px',
                      background: c('chatBubble-bg-right'),
                    })}
                  >
                    <Markdown content={message.content} theme={'dark'} />
                  </div>
                </div>
                <div
                  {...styleClass(['bubble-footer-wrapper'], {
                    marginLeft: 6,
                    justifyContent: 'flex-start',
                  })}
                >
                  <AnimatePresence>
                    {showDone && (
                      <motion.div
                        {...styleClass(['bubble-footer-loader-wrapper'], {
                          marginRight: 8,
                        })}
                        initial={{ opacity: '0%', x: 5 }}
                        animate={{ opacity: '100%', x: 0 }}
                        exit={{
                          opacity: '0%',
                          x: -20,
                          width: 0,
                          marginRight: 0,
                        }}
                        transition={{
                          ...motionEasing,
                          duration: 0.3,
                          delay: 0.5,
                        }}
                      >
                        <SvgIcon icon={Done_16x16} />
                      </motion.div>
                    )}
                  </AnimatePresence>
                  {status === 'delivered' && (
                    <motion.div
                      {...styleClass(['bubble-footer-status'])}
                      initial={{ x: 15, opacity: '0%' }}
                      animate={{ x: 0, opacity: '100%' }}
                      transition={{
                        ...motionEasing,
                        duration: 0.3,
                        delay: 0.75,
                      }}
                    >
                      Delivered
                    </motion.div>
                  )}

                  {status === 'typing' && (
                    <motion.div
                      {...styleClass(['bubble-footer-status'])}
                      initial={{ opacity: '100%' }}
                      exit={{ opacity: '0%' }}
                      transition={{
                        ...motionEasing,
                        duration: 0.25,
                      }}
                    >
                      Typing...
                    </motion.div>
                  )}

                  {status === 'typing' && (
                    <motion.div
                      {...styleClass(['bubble-footer-loader-wrapper'], {
                        marginLeft: 8,
                      })}
                      initial={{ opacity: '100%' }}
                      exit={{ opacity: '0%' }}
                      transition={{
                        ...motionEasing,
                        duration: 0.25,
                      }}
                    >
                      <Loader type={'threeBody'} />
                    </motion.div>
                  )}
                </div>
              </div>
            </motion.div>
          </div>
        )}
      </>
    )
  }
)
